<?php header("Access-Control-Allow-Origin:*");

require "vendor/autoload.php";
$dotenv = Dotenv\Dotenv::createImmutable(__DIR__);
$dotenv->load();

if (empty($_ENV)) {
    echo "config file does't exist";exit;
}

require 'SzPublish.class.php';
$publisher = SzPublish::get();
$version = $publisher->getAppVersion();
$developer = $publisher->getDeveloper();
if (!file_exists("apps/{$developer}/{$version}/www/index.php")) {
    $version = 'latest';
}
$ormConfigs = require_once "apps/{$developer}/{$version}/config/orm.config.php";
$databaseConfig = require_once "apps/{$developer}/{$version}/config/database.config.php";
$serversConfigs = $databaseConfig['MySql'];
$paymentConfig = $databaseConfig['Payment'];

$addOrmConfig = array(
    'ModuleItem' => array(
        'table'          => 'module_item',
        'columns'        => array('itemId', 'userId', 'itemDefId', 'type', 'freeCount', 'purchasedCount', 'commodityValue', 'expireTime', 'updateTime'),
        'autoIncrColumn' => 0,
        'diffUpColumns'  => array(4, 5, 6), // difference update columns
        'updateFilter'   => array(0, 1, 2, 3),
        'toArrayFilter'  => array(),
        'searchColumns'  => array(0, 1, 2, 3),
        'updateColumns'  => array(0),
        'jsonColumns'    => array(),
        'cacheColumn'    => 1,
        'shardColumn'    => 1,
        'pkColumn'       => 0,
        'deleteColumns'  => array(0),
        'tableShardCount'=> 5,
        'isList'         => true,
        'dbType'         => 'MySql',
        'cacheTime'      => 259200, // 3 days
    ),
    'ModuleProfileInfo' => array(
        'table'          => 'module_profile_infos',
        'columns'        => array('userId', 'infoType', 'info', 'time'),
        'autoIncrColumn' => null,
        'diffUpColumns'  => array(),
        'updateFilter'   => array(0, 1),
        'toArrayFilter'  => array(),
        'searchColumns'  => array(0, 1),
        'updateColumns'  => array(0, 1),
        'jsonColumns'    => array(2 => 512),
        'cacheColumn'    => 0,
        'shardColumn'    => 0,
        'pkColumn'       => 1,
        'deleteColumns'  => array(0, 1),
        'tableShardCount'=> 5,
        'isList'         => true,
        'dbType'         => 'MySql',
        'cacheTime'      => 259200, // 3 days
    ),
);

$ormConfigs = array_merge($ormConfigs,$addOrmConfig);
$noDeleteTable = array(
    'ft_guild_info','ft_guild_member_info'
);

$time = date("Y-m-d",strtotime("-33 day"));
$time = strtotime($time);
$level = 9;
$firstHandle = mysqli_connect($serversConfigs[0]['WRITER_HOST'][0], $serversConfigs[0]['WRITER_USER'], $serversConfigs[0]['WRITER_PWD'], $serversConfigs[0]['DB_NAME'], $serversConfigs[0]['WRITER_HOST'][1]);
$isFirst = true;
foreach ($serversConfigs as $serversConfig) {
    $handle = mysqli_connect($serversConfig['WRITER_HOST'][0], $serversConfig['WRITER_USER'], $serversConfig['WRITER_PWD'], $serversConfig['DB_NAME'], $serversConfig['WRITER_HOST'][1]);
    $paymentHandle = mysqli_connect($paymentConfig['WRITER_HOST'][0], $paymentConfig['WRITER_USER'], $paymentConfig['WRITER_PWD'], $paymentConfig['DB_NAME'], $paymentConfig['WRITER_HOST'][1]);
    $data1 = select("select count(*) as c from `module_profile` where (`lastLoginTime` < {$time} and `level` < {$level}) or (`lastLoginTime` is null)",$handle);
    $j = intval($data1[0]['c'] / 500) + 1;
    for ($i=0;$i<$j;$i++) {
        $list = select("select userId from `module_profile` where (`lastLoginTime` < {$time} and `level` < {$level}) or (`lastLoginTime` is null) order by `userId` desc limit 500",$handle);
        foreach ($list as $data) {
            $userId = $data['userId'];
            echo $serversConfig['DB_NAME']."　".$userId."\n";
            foreach ($ormConfigs as $ormConfig) {
                if (!in_array('userId',$ormConfig['columns'])) {
                    continue;
                }
                if ($ormConfig['tableShardCount']) {
                    $table = $ormConfig['table'].($userId % $ormConfig['tableShardCount']);
                } else {
                    $table =  $ormConfig['table']."\n";
                }
                $sql = "delete from {$table} where `userId` = {$userId}";
                delete($sql,$handle);
            }
            delete("delete from module_sns where `userId` = {$userId}",$firstHandle);
            delete("delete from module_profile where `userId` = {$userId}",$handle);
            delete("delete from `module_payment` where `userId` = {$userId}",$paymentHandle);
        }
    }
    delete("delete from `ft_friend_code`",$handle);
    if (!$isFirst) {
        mysqli_close($handle);
    } else {
        $isFirst = false;
    }

    mysqli_close($paymentHandle);
}
mysqli_close($firstHandle);
echo 'end';

 function select($sql,$handle) {
    /* @var mysqli_result $result */
    $result = mysqli_query($handle, $sql);
    for ($i = 0; $array[$i] = mysqli_fetch_assoc($result); $i++);
    array_pop($array);
    mysqli_free_result($result);
    return $array;
}

function delete($sql,$handle) {
    $result = mysqli_query($handle,$sql);
    return $result;
}

